<!--应用新建/编辑抽屉弹框组件-->
<template>
  <edit-drawer
    v-model:visible="showState"
    :title="title"
    show-submit
    :submit-loading="saveLoading"
    @submit="handleSave"
    @close="handleClose"
    @cancel="handleClose"
  >
    <dynamics-form ref="formRef" :setting="setting" :model="model" />
  </edit-drawer>
</template>

<script>
import { computed, ref } from 'vue'
import { DynamicsForm, EditDrawer, message } from '@bairong/vix'
import { cityData } from '@libs/data/city'
import { addApi, updateApi } from '@/api/organization'

export default {
  name: 'OrganizationEditDialog',
  components: {
    EditDrawer,
    DynamicsForm
  },
  props: {
    mode: {
      type: Number,
      default: undefined
    }
  },
  emits: ['finish'],
  setup(props, { emit }) {
    // 抽屉显示状态
    const showState = ref(false)
    // 当前操作标识 add添加 edit编辑
    const operateType = ref('add')
    // 保存按钮loading控制
    const saveLoading = ref(false)
    // 根据操作标识，计算抽屉标题
    const title = computed(() => (operateType.value === 'add' ? '新建机构' : '编辑机构'))

    const initModel = () => ({
      sourceName: '',
      contactMan: '',
      sourceType: props.mode,
      contactType: '',
      email: '',
      serviceArea: ''
    })
    // 编辑表单数据
    const model = ref(initModel())
    // 表单Ref
    const formRef = ref(null)
    // 编辑表单配置
    const setting = ref([
      {
        name: 'sourceName',
        label: '机构名称',
        placeholder: '请输入机构名称',
        type: 'input',
        rules: [
          { required: true, message: '请输入机构名称', trigger: 'blur' },
          {
            pattern: /^[\u4E00-\u9FA5a-zA-Z0-9-_()（）]{2,30}$/,
            message: '仅支持2-30位中文、英文、数字、中划线、下划线、括号',
            trigger: 'blur'
          }
        ]
      },
      {
        name: 'contactMan',
        label: '联系人',
        type: 'input',
        placeholder: '请输入联系人',
        rules: [
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9·_-]{2,20}$/,
            message: '仅支持2-20位中文、英文、数字、符号·_-',
            trigger: 'blur'
          }
        ]
      },
      {
        name: 'contactType',
        label: '联系方式',
        type: 'input',
        placeholder: '请输入联系方式',
        rules: [
          {
            pattern: /^((0\d{2,3}(-?)\d{1,8})|(1[3-9]\d{9}))$/,
            message: '请输入正确的电话号码',
            trigger: 'blur'
          }
        ]
      },
      {
        name: 'serviceArea',
        label: '业务区域',
        placeholder: '请选择业务区域',
        props: {
          multiple: true
        },
        options: cityData,
        type: 'select',
        rules: [
          {
            required: true,
            type: 'array',
            message: '请选择业务区域',
            trigger: 'change'
          }
        ]
      }
    ])
    // 对外方法，根据参数判断是新增还是编辑
    const show = row => {
      if (row) {
        // 参数存在为编辑 将数据赋予form
        const {
          sourceName,
          contactMan,
          sourceType,
          contactType,
          id,
          serviceArea
        } = row
        // 只有使用技能非空时，应用所属客户不可编辑
        model.value = {
          id,
          sourceType,
          contactMan,
          sourceName,
          contactType,
          serviceArea: serviceArea.split(',').map(x => Number(x))
        }
        operateType.value = 'edit'
        showState.value = true
      } else {
        // 参数不存在，为新建操作，初始化空数据
        model.value = initModel()
        operateType.value = 'add'
        showState.value = true
      }
    }
    // 关闭事件
    const handleClose = () => {
      showState.value = false
      formRef.value.resetFields()
    }

    // 保存事件
    const handleSave = () => {
      formRef.value.validate().then(() => {
        const params = { ...model.value }
        params.serviceArea = params.serviceArea.join(',')
        saveLoading.value = true;
        // 根据不同操作调用不同API
        (operateType.value === 'add' ? addApi : updateApi)(params)
          .then(() => {
            const msg = operateType.value === 'add' ? '保存成功' : '修改成功'
            message.success(msg)
            saveLoading.value = false
            handleClose()
            // 保存结束事件通知
            emit('finish', operateType.value)
          })
          .catch(err => {
            message.error(err)
            saveLoading.value = false
          })
      })
    }

    return {
      showState,
      title,
      saveLoading,
      formRef,
      model,
      setting,
      show,
      handleSave,
      handleClose
    }
  }
}
</script>
